package com.yth.utils;

import java.util.function.BooleanSupplier;

/**
 * 错误消息构建工具类，用于构建统一格式的错误消息
 *
 * @author yutianhong
 * @version 1.0
 * @since 2025/5/27 16:56
 */
public class ErrorMessageBuilder {
    private final StringBuilder messageBuilder = new StringBuilder();

    /**
     * 创建一个新的ErrorMessageBuilder实例
     */
    public static ErrorMessageBuilder builder() {
        return new ErrorMessageBuilder();
    }

    public static String of(String key, String value) {
        return builder().append(key, value).build();
    }

    public ErrorMessageBuilder append(String key, String value) {
        appendKeyValue(key, value);
        return this;
    }

    public ErrorMessageBuilder appendIfPresent(String key, String value) {
        if (key != null && !key.isEmpty() && value != null && !value.isEmpty()) {
            appendKeyValue(key, value);
        }
        return this;
    }

    public ErrorMessageBuilder appendIf(String key, String value, BooleanSupplier condition) {
        if (condition.getAsBoolean()) {
            appendKeyValue(key, value);
        }
        return this;
    }

    /**
     * 构建最终的错误消息字符串
     */
    public String build() {
        return messageBuilder.toString();
    }

    private void appendKeyValue(String key, String value) {
        if (messageBuilder.length() > 0) {
            messageBuilder.append(",");
        }
        messageBuilder.append(key).append(":").append(value);
    }
}

